package com.example.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.zip.Inflater;

import com.example.test.FriLineActivity.TimeLineAdapter;
import com.example.test.PullDownView.OnPullDownListener;
import com.example.test.model.AsyncDownHeadImageTask;
import com.example.test.model.AsyncDownHeadImgTask;
import com.example.test.model.CommonFunc;
import com.example.test.model.Constants;
import com.example.test.model.HashDataProcessor;
import com.example.test.model.NetAPI;
import com.example.test.model.QQAPI;
import com.example.test.model.SinaAPI;
import com.example.test.model.SinaJsonAnalyzer;
import com.example.test.model.SohuWeiboAPI;
import com.sohu.microblog.http.blogapi.SohuApi;
import com.tencent.weibo.sdk.android.model.GlobalVar;

import android.R.drawable;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class CommentActivity extends Activity  implements OnPullDownListener{

	private ListView lvTimeline=null;
    private PullDownView mPullDownView;
	List<HashMap<String, String>> lArrTimeline = null;
	HashMap<String, Drawable> mapHeadImgList=new HashMap<String,Drawable>();
	CommentLineAdapter adapter;
	Drawable [] drawables;
	String activity_type =null;
	String sinaMaxid="";
	String sohuMaxid="";
	String netMaxid="";
	
	private void judgeOnMoreFirst(List<HashMap<String,String>> tempList)
	{
		String resource=tempList.get(0).get("resource");
		String id=tempList.get(0).get("id");
		if((resource.equals("sina")&&id.equals(sinaMaxid))||(resource.equals("sohu")&&id==sohuMaxid)||(resource.equals("netease")&&id==netMaxid))
	    tempList.remove(0);
	}

	
	 Handler handler=new Handler()
	{

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what==Constants.MSG_DOWNIMG_SUCCESS)
			{
				HashMap<String, Object> map=(HashMap<String, Object>)msg.obj;
				String position=(String)map.get("position");
				mapHeadImgList.put(position, (Drawable)map.get("img"));
				adapter.notifyDataSetChanged();
			}
			else if(msg.what==Constants.MSG_GETCOMMENT_SUCCESS)
			{
				mPullDownView.notifyDidLoad();
				mPullDownView.notifyDidRefresh();
				mPullDownView.notifyDidMore();
				List<HashMap<String,String>> lArrTemp=(List<HashMap<String,String>>)msg.obj;
				HashDataProcessor.CommentDataProcess(lArrTemp);
				if(lArrTemp.size()!=0)
				{
				judgeOnMoreFirst(lArrTemp);
				if(lArrTemp.get(0).get("resource").equals("sina"))
				{
					sinaMaxid=lArrTemp.get(lArrTemp.size()-1).get("id");
				}
				else if(lArrTemp.get(0).get("resource").equals("sohu"))
				{
					sohuMaxid=lArrTemp.get(lArrTemp.size()-1).get("id");
				}
				else if(lArrTemp.get(0).get("resource").equals("netease"))
				{
					netMaxid=lArrTemp.get(lArrTemp.size()-1).get("id");
				}
				}
				if(lArrTimeline==null)
				{
					lArrTimeline=lArrTemp;
				}
				else if(lArrTimeline.size()==0)
				{
					lArrTimeline.addAll(lArrTemp);
				}
				else
				{
					
					lArrTimeline.addAll(lArrTemp);
				}
				Collections.sort(lArrTimeline,new StatusListComparator());
				if(adapter==null)
				{
					adapter=new CommentLineAdapter(CommentActivity.this,handler, lArrTimeline,drawables,activity_type);
				    lvTimeline.setAdapter(adapter);
				}
				else
					adapter.notifyDataSetChanged();
				mPullDownView.enableAutoFetchMore(true, 1);
				for(int i=0;i<lArrTemp.size();i++)
			       {
			       Thread thread=new Thread(new AsyncDownHeadImgTask(handler, lArrTemp.get(i).get("resource")+lArrTemp.get(i).get("id"), lArrTemp.get(i).get("userprofile_image_url")));
			       thread.start();
			       }
			}
			else if(msg.what==Constants.MSG_DELETECOMMENT_SUCCESS)
			{
				SinaAPI.getCommentByMe(handler, GlobalVar .sinaUid);
				Toast.makeText(CommentActivity.this, "评论删除成功", 1000).show();
			}
			else if(msg.what==Constants.MSG_DELETECOMMENT_FAIL)
			{
				Toast.makeText(CommentActivity.this, "评论删除失败，错误码："+msg.obj, 1000).show();
			}
			
		}
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activity_type="CommentByOthers";
		setContentView(R.layout.activity_friline);
		 mPullDownView = (PullDownView) findViewById(R.id.pull_down_view);
	        mPullDownView.setOnPullDownListener(this);
	        lvTimeline = mPullDownView.getListView();
			GlobalVar.changed=true;
	}
	
	@Override
	protected void onResume() {
        if(GlobalVar.changed)
        {
        	if(lArrTimeline!=null)
        	{
        		lArrTimeline.clear();adapter.notifyDataSetChanged();
        	}
        	SinaAPI.getCommentToMe(handler,GlobalVar.sinaUid,"0",5);
			NetAPI.getCommentToMe(handler,"0",5);
			SohuWeiboAPI.getCommentToMe(handler,"0",5);
			GlobalVar.changed=false;
        }
		super.onResume();
	}

	@Override
    public void onRefresh() {
		SinaAPI.getCommentToMe(handler, GlobalVar.sinaUid, "0", 5);
		NetAPI.getCommentToMe(handler, "0", 5);
		SohuWeiboAPI.getCommentToMe(handler,"0",5);
		 lArrTimeline.clear();
    }
 
    @Override
    public void onMore() {
    	
    	if(!sinaMaxid.equals(""))
    	       SinaAPI.getCommentToMe(handler, GlobalVar.sinaUid, sinaMaxid, 5);
    	else
    	      SinaAPI.getCommentToMe(handler, GlobalVar.sinaUid, "0", 5);
    	if(!netMaxid.equals(""))
 	       NetAPI.getCommentToMe(handler, netMaxid, 5);
 	else
 		NetAPI.getCommentToMe(handler, "0", 5);
    	if(!sohuMaxid.equals(""))
  	       SohuWeiboAPI.getCommentToMe(handler, sohuMaxid, 5);
  	else
  		SohuWeiboAPI.getCommentToMe(handler, "0", 5);
    	}
    
    
    
    class CommentLineAdapter extends BaseAdapter
    {
     Context context;
     List<HashMap<String, String>> lsHashData;
     Drawable []drawables;
     Handler handler;
     String activity_type;
     public CommentLineAdapter(Context context,Handler handler,List<HashMap<String, String>> data,Drawable []drawables,String activity_type)
     {
   	  this.handler=handler;
   	  this.context=context;
   	  this.drawables=drawables;
   	  this.lsHashData=data;
   	  this.activity_type=activity_type;
     }
   	@Override
   	public int getCount() {
   		// TODO Auto-generated method stub
   		return lsHashData.size();
   	}

   	@Override
   	public Object getItem(int arg0) {
   		// TODO Auto-generated method stub
   		return null;
   	}

   	@Override
   	public long getItemId(int arg0) {
   		// TODO Auto-generated method stub
   		return 0;
   	}

   	@Override
   	public View getView(final int position, View convertView, ViewGroup parent) {
   		{
   			Log.v("count", position+"");
   			if(convertView==null)
   			{
   	      	convertView=LayoutInflater.from(context).inflate
   			    (R.layout.comment_item,null);
   			}
   		RelativeLayout rlcommentitem=(RelativeLayout)convertView.findViewById(R.id.rlcommentitem);
   		TextView tvUsername=(TextView)convertView.findViewById(R.id.tvusername);
   		TextView tvcretime=(TextView)convertView.findViewById(R.id.tvcretime);
   		TextView tvsource=(TextView)convertView.findViewById(R.id.tvsource);
   		TextView tvstatustext=(TextView)convertView.findViewById(R.id.tvstatustext);
   		TextView tvSourceUser=(TextView)convertView.findViewById(R.id.tvSourceUser);
   		TextView tvCommentedText=(TextView)convertView.findViewById(R.id.tvCommentedText);
   		//new String[]{"created_at","userscreen_name","source","text","reposts_count","comments_count","attitudes_count","profile_image_url"},
   		//new int[]{R.id.tvcretime,R.id.tvusername,R.id.tvsource,R.id.tvstatustext,R.id.tvstatusreposts,R.id.tvstatuscomment,R.id.tvstatusattitude,R.id.ivuserhead
   		tvUsername.setText(lsHashData.get(position).get("userscreen_name"));
   		tvcretime.setText(lsHashData.get(position).get("created_at"));
   		tvsource.setText(lsHashData.get(position).get("source"));
   		tvstatustext.setText(lsHashData.get(position).get("text"));
   		tvSourceUser.setText(lsHashData.get(position).get("statususername"));
   		tvCommentedText.setText(lsHashData.get(position).get("statustext"));
   		if(lsHashData.get(position).get("resource").equals("sina"))
   		{
   			ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
   			ivResource.setImageResource(R.drawable.ic_com_sina_weibo_sdk_logo);
   		}
   		else if(lsHashData.get(position).get("resource").equals("netease"))
   		{
   			ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
   			ivResource.setImageResource(R.drawable.net_logo);
   		}
   		else if(lsHashData.get(position).get("resource").equals("sohu"))
   		{
   			ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
   			ivResource.setImageResource(R.drawable.sohu_logo);
   		}
   		rlcommentitem.setOnClickListener(new View.OnClickListener() {
   			
   			@Override
   			public void onClick(View arg0) {
   				View view=LayoutInflater.from(((CommentActivity)context).getParent())
   						  .inflate(R.layout.dlg_commentbymeclick, null);
   				final AlertDialog dlg = new AlertDialog.Builder  (((CommentActivity)context).getParent()).create();
   				Button btSeeWeibo=(Button)view.findViewById(R.id.btSeeWeibo);
   				Button btSeeHome=(Button)view.findViewById(R.id.btSeeHome);
   				btSeeHome.setOnClickListener(new Button.OnClickListener() {
   					
   					@Override
   					public void onClick(View arg0) {
   					Intent intent =new Intent(context, HomeActivity.class);
   					if( activity_type.equals("CommentByMe"))
   					intent.putExtra("uid",lsHashData.get(position).get("statususerid"));
   					else if( activity_type.equals("CommentByOthers"))
   					intent.putExtra("uid",lsHashData.get(position).get("userid"));

                       intent.putExtra("activity_type", lsHashData.get(position).get("resource"));
   					
   					context.startActivity(intent);
   					dlg.cancel();
   					}
   				});
   				
   				btSeeWeibo.setOnClickListener(new Button.OnClickListener() {
   					
   					@Override
   					public void onClick(View arg0) {
   						Intent intent =new Intent(context, WeiBoDetailActivity.class);
   						intent.putExtra("weiboID",lsHashData.get(position).get("statusid"));
   						intent.putExtra("resource", lsHashData.get(position).get("resource"));
   						context.startActivity(intent);
   						dlg.cancel();
   					}
   				});
   				 dlg.setView(view);
   				 dlg.show();
   			}
   		});
   	}
   		String headid=lsHashData.get(position).get("resource")+lsHashData.get(position).get("id");
   		if(mapHeadImgList.get(headid)!=null)
   		{
   			ImageView ivUserHead =(ImageView) convertView.findViewById(R.id.ivuserhead);
   			ivUserHead.setImageDrawable(mapHeadImgList.get(headid));
   		}
   		else
   		{
   			ImageView ivUserHead =(ImageView) convertView.findViewById(R.id.ivuserhead);
   			ivUserHead.setImageResource(R.drawable.nohead);
   		}
   		return convertView;
   	}
    
    
    
    }

 
	 
 }

